<!-- 电子签章管理页面  wk-2022-7-14 -->
<script setup lang='ts'>
import {onBeforeMount, ref, reactive, nextTick} from 'vue'
import { ElMessage, ElMessageBox} from 'element-plus'
import {HeaderData, Operation as Oper, RowOperbuttons} from '@/components/dTable/dTable'
import {OperButton, SearchButton, SearchFromItem, SearchFromJustify} from '@/components/dTable/dHeader'
import {PageConfig, defaultPage, defaultPageSize, defaultPageSizes, defaultLayout} from '@/components/dTable/dFooter'
import {ColorTheme, ColorRed, DialogType} from '@/api/config'
import {getSignList, SignInfor, TableOperation, SignFormInfor, SearchSignFromData, getOrgInfor, delDict, getDictionaries} from '@/api/baseSetting/labSign'
import operation from '@/components/dTable/components/operation.vue'
import {SeleteData} from '@/api/config'
import pageContainer from '@/components/pageContainer.vue'
import dTablePromote from '@/components/dTable/dTablePromote.vue'
import color from './color.vue'
import signImg from './img.vue'
// import {useStore} from '@/store/index'
import {transfDicArrData, getObjectByKey, transfArrData} from '@/util/common'
import addSign from './addSign.vue'
// const store = useStore()

//当前页面 表格数据 定义
const tableData = ref<Array<SignInfor&RowOperbuttons>>([])

//显示加载状态
const showLoading = ref(false)

//下拉 类型 语言 抬头 纸张 定义
const sealTypeNameList = ref<Array<SeleteData>>([])

const labIdList = ref<Array<SeleteData>>([])

//表格头部数据定义
const tableHeaderData = ref<Array<HeaderData>>([
  {prop:'author', label:'作者', columnType:'text', align:'left', 'min-width':'100'},
  {prop:'categoryName', label:'类别', columnType:'text', align:'left', 'min-width':'100'},
  {prop:'name', label:'书籍名字', columnType:'text', align:'left', 'min-width':'100'},
  {prop:'price', label:'价格', columnType:'text', align:'left', 'min-width':'100'},
  {prop:'cover', label:'封面图片', columnType:'slot', align:'left', 'min-width':'100'},
  {prop:'description', label:'书籍描述', columnType:'text', align:'left', 'min-width':'100'},
  {prop:'oper', label:'操作', columnType:'slot', align:'left', 'min-width':'100'}
])

//搜索项数据定义
const searchFromItems = ref<Array<SearchFromItem>>([
  {label:'书籍名称', placeholder:'请选择书籍名称', prop:'name',  type:'input'},
  {label:'书籍类型', placeholder:'请选择书籍类型', prop:'categoryName', type:'selete', changeSubmit:true, seleteData:sealTypeNameList.value}
])

const searchFromData = reactive<any>({name:null, categoryName:null})


//表头按钮
const operButtons = ref<Array<OperButton>>([
  {label:'新增', type:'noraml', iconConfig:{icon:'add', type:'custom'}, code:'add'}
])

//分页配置
const pageConfig = ref<PageConfig>({
  currentPage:defaultPage,
  pageSize:defaultPageSize,
  pageSizes:defaultPageSizes,
  total:0,
  disabled:false,
  layout:defaultLayout
})

//表单靠左还是靠右
const searchFromJustify = ref<SearchFromJustify>('flexStart')

//搜索按钮配置
const searchButtons = ref<Array<SearchButton>>([
  {type:'search'},
  {type:'clear'}
])


//后端数据拼接字段事件
const setTableData = (data:Array<any>) => {
  console.log('hhhhhhhhhhhhhhhh', data)

  const dataArr:Array<SignInfor&RowOperbuttons> = []
  data.forEach((item) => {
    const rowOperButtonsStop:Array<OperButton> = [
      {code:'edit', label:'编辑',   type: 'noraml',    iconConfig: {
        icon: 'common-edit',
        type: 'custom',
        color: '#1C9399',
        size: 20
      }},
      {code:'del', label:'删除',  type: 'noraml', iconConfig: {
        icon: 'common-delete',
        type: 'custom',
        color: 'rgb(225,56,72)',
        size: 20
      }}
    ]
    item.price = item.price + '元'
    dataArr.push({...item, oper:rowOperButtonsStop})
  })
  tableData.value = dataArr
}

//搜索数据事件
const searchData = (resetPage?:boolean) => {
  showLoading.value = true
  if (resetPage) pageConfig.value.currentPage = 1

  getSignList({name:searchFromData.name, categoryId:searchFromData.categoryName, pageNo:pageConfig.value.currentPage, pageSize:pageConfig.value.pageSize}).then((res) => {
    const {data} = res.data
    pageConfig.value.total = res.data.data.total === null ? 0 : res.data.data.total
    if (data) {
      setTableData(data.list)
    } else {
      tableData.value = []
    }
  }).catch((error) => {
    console.warn(error)
  })


}

//查询实验室列表
const setOrglist = () => {
  searchData()
//   getOrgInfor().then((res) => {
//     const {data} = res.data
//     data?.forEach((item) => {
//       labIdList.value.push({label:item.structureName ? item.structureName : '', value:item.orgId ? item.orgId : ''})
//     })
//     if (labIdList.value.length > 0) {
//     //   searchFromData.labId = labIdList.value[0].value
//     }
//     searchData()
//   }).catch((error) => {
//     console.warn(error)
//   })
}

//搜索事件
const onSubmit = () => {
  searchData(true)
}

//清除搜索栏数据事件
const clearForm = () => {
  searchData(true)
}

//清空搜索表单事件
const onFormClear = () => {
  clearForm()
  searchData(true)
}


//显示弹窗
const showDialog = ref(false)

//弹窗类型
const dialogType = ref<DialogType>('add')

//基础电子签章数据模板
const baseSignFromInfor = {categoryId:'', categoryName:'', author:'', cover:'', description:'',  price:'', name:''}

//编辑的电子签章数据
const currSignFromData = ref<SignFormInfor>({categoryId:'', categoryName:'', author:'', cover:'', description:'',  price:'', name:''})

//清除数据
const clearDialogData = () => {
  currSignFromData.value = {...baseSignFromInfor}
}
// 删除接口
const setdelDict = (id: string) => {
  delDict(id).then((res) => {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    searchData(true)

  })
}
//操作按钮事件
const onOperation = (name:TableOperation, row:any) => {
  if (name === 'add') {
    clearDialogData()
    // currSignFromData.value.labId = searchFromData.labId
    dialogType.value = 'add'
    showDialog.value = true
  }
}

//
// const openSignInfor = (row:SignInfor) => {
//   const signAllInfor:SignFormInfor = {...{labId:searchFromData.labId, remark:row.remark, status:row.status, sealType:row.sealType, picture:row.picture, id:row.id} as SignFormInfor}
//   if (signAllInfor.status === '停用') {
//     signAllInfor.status = 1
//     ElMessageBox.confirm(
//       '确认启用印章：' + row.sealTypeName,
//       '启用确认',
//       {
//         confirmButtonText: '确认',
//         cancelButtonText: '取消',
//         type: 'warning'
//       }
//     ).then(() => {
//       return stopSign(signAllInfor).then(() => {
//         searchData(true)
//         ElMessage.success('启用成功！')
//       }).catch((error) => {
//         console.warn(error)
//       })
//     }).catch((error) => {
//       console.warn(error)
//     })
//   } else {
//     signAllInfor.status = 0
//     ElMessageBox.confirm(
//       '确认停用印章：' + row.sealTypeName,
//       '停用确认',
//       {
//         confirmButtonText: '确认',
//         cancelButtonText: '取消',
//         type: 'warning'
//       }
//     ).then(() => {
//       return stopSign(signAllInfor).then(() => {
//         searchData(true)
//         ElMessage.success('停用成功！')
//       }).catch((error) => {
//         console.warn(error)
//       })
//     }).catch((error) => {
//       console.warn(error)
//     })
//   }
// }

// 展示放大框
const dialogVisible = ref(false)

const imgUrl = ref('')

const clickIt = (data) => {
  imgUrl.value = data.value
  dialogVisible.value = true
}

//关闭窗口事件
const onClose = () => {
  showDialog.value = false
  searchData()
}

//分页尺寸改变事件
const onSizeChange = () => {
  searchData(true)
}

//当前页改变事件
const onCurrentChange = () => {
  searchData()
}

//编辑电子签章信息事件
const editSignInfor = (row:SignInfor) => {
  currSignFromData.value = {categoryId:row.categoryId, categoryName:row.categoryName, description:row.description, author:row.author, name:row.name, price:row.price, cover:row.cover, id:row.id}
  dialogType.value = 'edit'
  showDialog.value = true
}

//操作插槽事件（编辑，查看，删除）事件
const cellOperation = (name:string, row:any) => {
  if (name === 'edit') {
    editSignInfor(row)
  }
  else if (name === 'del') {
    ElMessageBox.confirm('确认删除：' + row.name + '书籍', '删除确认', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      setdelDict(row.id)
    }).catch((error) => {
      console.warn(error)
    })
  }
}

//DOM即将挂载
onBeforeMount(() => {
  setOrglist()
  // 获取印章类型
  //   store.dispatch('common/getDicData', {dicName:'seal_type'}).then((res) => {
  //     const item = getObjectByKey(searchFromItems.value, 'prop', 'sealTypeName')
  //     if (item && item.type === 'selete') {
  //       item.seleteData = transfDicArrData(res)
  //     }
  //   })
  getDictionaries().then((res) => {
    const dataList = res.data.data as any
    console.log('查出来的数据0', sealTypeNameList.value, res.data.data)
    const arr:Array<SeleteData> = transfArrData(dataList.list, {'name':'label', 'id':'value'})
    arr.forEach((item) => {
      sealTypeNameList.value.push(item)
    })

  })
})
</script>

<template>
  <page-container>
    <d-table-promote
      :show-index="true"
      :label-width="88"
      :oper-buttons="operButtons"
      :table-data="tableData"
      :table-header-data="tableHeaderData"
      :page-config="pageConfig"
      :search-form-data="searchFromData"
      :search-form-items="searchFromItems"
      :search-from-justify="searchFromJustify"
      :search-buttons="searchButtons"
      @form-submit="onSubmit"
      @form-clear="onFormClear"
      @operation="onOperation"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
    >
      <template #oper="scope">
        <operation :row="scope.row" :col="scope.item" @opertion-click="cellOperation" />
      </template>
      <template #cover="scope">
        <signImg :row="scope.row" :col="scope.item" @click-it="clickIt" />
      </template>
    </d-table-promote>
    <el-dialog v-model="dialogVisible" width="400">
      <img w-full :src="imgUrl" alt="Preview Image">
    </el-dialog>
  </page-container>
  <add-sign v-if="showDialog" :show-dialog="showDialog" :dialog-type="dialogType" :sign-data="currSignFromData" @close="onClose" />
</template>

<style scoped>
</style>